<?php
class ModelLocalisationWeightClass extends Model {
	public function addWeightClass($data) {
		$this->db->query("INSERT INTO  @@weight_class SET value = " . (float)$data['value']);

		$weight_class_id = $this->db->getLastId();

		foreach ($data['weight_class_description'] as $language_id => $value) {
			$this->db->query("INSERT INTO  @@weight_class_description SET weight_class_id = " . $weight_class_id . ", language_id = " . (int)$language_id . ", title = '" . ES($value['title']) . "', unit = '" . ES($value['unit']) . "'");
		}
	}

	public function editWeightClass($weight_class_id, $data) {
		$this->db->query("UPDATE  @@weight_class SET value = " . (float)$data['value'] . " WHERE weight_class_id = " . (int)$weight_class_id);

		$this->db->query("DELETE FROM  @@weight_class_description WHERE weight_class_id = " . (int)$weight_class_id);

		foreach ($data['weight_class_description'] as $language_id => $value) {
			$this->db->query("INSERT INTO  @@weight_class_description SET weight_class_id = " . (int)$weight_class_id . ", language_id = " . (int)$language_id . ", title = '" . ES($value['title']) . "', unit = '" . ES($value['unit']) . "'");
		}
	}

	public function deleteWeightClass($weight_class_id) {
		$this->db->query("DELETE FROM  @@weight_class WHERE weight_class_id = " . (int)$weight_class_id);
		$this->db->query("DELETE FROM  @@weight_class_description WHERE weight_class_id = " . (int)$weight_class_id);
	}

	public function getWeightClasses($filter = null) {
		$sql = "SELECT * FROM  @@weight_class wc LEFT JOIN  @@weight_class_description wcd ON (wc.weight_class_id = wcd.weight_class_id) WHERE wcd.language_id = " . (int)C('config_language_id');

		if ($filter) {
			$sql .= $filter->sort('title');
			$sql .= $filter->limit();
		}

		$query = $this->db->query($sql);

		return $query->rows;
	}

	public function getWeightClass($weight_class_id) {
		return $this->db->queryOne("SELECT * FROM  @@weight_class wc LEFT JOIN  @@weight_class_description wcd ON (wc.weight_class_id = wcd.weight_class_id) WHERE wc.weight_class_id = " . (int)$weight_class_id . " AND wcd.language_id = " . (int)C('config_language_id'));
	}

	public function getWeightClassDescriptionByUnit($unit) {
		return $this->db->queryOne("SELECT * FROM  @@weight_class_description WHERE unit = '" . ES($unit) . "' AND language_id = " . (int)C('config_language_id'));
	}

	public function getWeightClassDescriptions($weight_class_id) {
		$weight_class_data = array();

		$query = $this->db->query("SELECT * FROM  @@weight_class_description WHERE weight_class_id = " . (int)$weight_class_id);

		foreach ($query->rows as $result) {
			$weight_class_data[$result['language_id']] = array(
				'title' => $result['title'],
				'unit'  => $result['unit']
			);
		}

		return $weight_class_data;
	}

	public function getTotalWeightClasses() {
      	return $this->db->queryOne("SELECT COUNT(*) AS total FROM  @@weight_class");
	}
}
?>